package com.wl.shop.web;

import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.web.Servlets;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Maps;
import com.wl.shop.entity.Article;
import com.wl.shop.entity.Category;
import com.wl.shop.entity.FieldArticle;
import com.wl.shop.model.DataTableResult;
import com.wl.shop.model.RestResponse;
import com.wl.shop.utils.Constants;
import com.wl.shop.utils.DateUtils;
import com.wl.shop.utils.StringUtils;
import com.wl.shop.utils.UserUtils;

@Controller
@RequestMapping("${adminPath}/article")
public class ArticleController extends BaseController {
	
	@GetMapping("list")
	public String list(Model model){
		logger.info("跳转文章列表---");
		model.addAttribute("tree", UserUtils.getCategoryTreeString());
		return "cms/article/list";
	}
	
	@PostMapping("list")
	@ResponseBody
	public DataTableResult list(@RequestParam(value = "cid",required = false)String cid,String aodata,ServletRequest request){
		logger.info("设置datatable的值",aodata);
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
		String name = (String)searchParams.get("name");
		String startTime = (String)searchParams.get("startTime");
		String endTime = (String)searchParams.get("endTime");
		Map<String,Object>	map =Constants.convertToMap(aodata);
		int echo = (Integer) map.get("sEcho");
		int start = (Integer)map.get("iDisplayStart");
		int pageSize = (Integer)map.get("iDisplayLength");
		int pageNum = start/pageSize==0?1:(start/pageSize+1);
		pageSize=pageSize<0?1000:pageSize;
		DataTableResult result = new DataTableResult();
		result.setSEcho(echo);
		EntityWrapper<Article> wapper = new EntityWrapper<Article>();
		wapper.eq("is_del", false);
		if(StringUtils.isNotBlank(cid) && !"1".equals(cid)){
			wapper.eq("category_id", cid);
			wapper.orderBy("sort",true);
		}else{
			wapper.orderBy("create_date",false);
		}
		if(StringUtils.isNotBlank(name)){
			wapper.like("title", name);
		}else{
			searchParams.remove("name");
		}
		if(StringUtils.isNotBlank(startTime)){
			wapper.ge("create_date", DateUtils.parse(startTime, "yyyy-MM-dd hh:mm:ss"));
		}else{
			searchParams.remove("startTime");
		}
		if(StringUtils.isNotBlank(endTime)){
			wapper.le("create_date", DateUtils.parse(endTime, "yyyy-MM-dd hh:mm:ss"));
		}else{
			searchParams.remove("endTime");
		}
		
		Page<Article> page = articleService.selectPage(new Page<Article>(pageNum,pageSize), wapper);
		result.setAaData(page.getRecords());
		result.setITotalRecords(page.getTotal());
		result.setITotalDisplayRecords(page.getTotal());
		if(!searchParams.isEmpty()){
			result.setSColumns(Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
		}
		return result;
	}
	
	@GetMapping("add")
	public String add(String cid,Model model){
		if("1".equals(cid)){
			return "redirect:${adminPath}/article/list";
		}
		Category category = categoryService.selectById(cid);
		model.addAttribute("category", category);
//		model.addAttribute("tree", UserUtils.getCategoryTreeString());
		return "cms/article/add";
	}
	
	/**
	 * 
	 * @param article 
	 * @return
	 */
	@PostMapping("add")
	@ResponseBody
	public RestResponse add(@RequestBody Article article){
		if(StringUtils.isBlank(article.getCategoryId())){
			return RestResponse.failure("文章所属栏目不能为空");
		}
		if(StringUtils.isBlank(article.getTitle())){
			return RestResponse.failure("文章标题不能为空");
		}
		if(article.getSort() == 0 || article.getSort() == null){
			article.setSort(articleService.selectMaxSort(article.getCategoryId())+10);
		}
		Category  category = categoryService.selectById(article.getCategoryId());
		if(category == null){
			return RestResponse.failure("文章所属栏目ID不正确");
		}
		article.setCategoryName(category.getName());
		articleService.saveOrUpdate(article);
		
		List<FieldArticle>  fieldList  =article.getSelfField();
		if(fieldList != null && fieldList.size()>0){
			for (FieldArticle fieldArticle : fieldList) {
				fieldArticle.setArticleId(article.getId());
			}
			fieldArticleService.insertBatch(fieldList);
		}
		return RestResponse.success();
	}
	
	@GetMapping("edit")
	public String edit(String aid,Model model){
		Article article = articleService.selectById(aid);
		model.addAttribute("article", article);
		model.addAttribute("tree", UserUtils.getCategoryTreeString());
		return "cms/article/edit";
	}
	
	@PostMapping("edit")
	@ResponseBody
	public RestResponse edit(@RequestBody Article article){
		if(article.getId() == null || article.getId() == 0){
			return RestResponse.failure("文章ID不能为空");
		}
		if(StringUtils.isBlank(article.getCategoryId())){
			return RestResponse.failure("文章所属栏目不能为空");
		}
		if(StringUtils.isBlank(article.getTitle())){
			return RestResponse.failure("文章标题不能为空");
		}
		if(article.getSort() == 0 || article.getSort() == null){
			article.setSort(articleService.selectMaxSort(article.getCategoryId())+10);
		}
		Category  category = categoryService.selectById(article.getCategoryId());
		if(category == null){
			return RestResponse.failure("文章所属栏目ID不正确");
		}
		article.setCategoryName(category.getName());
		articleService.saveOrUpdate(article);
		
		Map<String,Object> map = Maps.newHashMap();
		map.put("article_id", article.getId());
		fieldArticleService.deleteByMap(map);
		
		List<FieldArticle>  fieldList  =article.getSelfField();
		if(fieldList != null && fieldList.size()>0){
			for (FieldArticle fieldArticle : fieldList) {
				fieldArticle.setArticleId(article.getId());
			}
			fieldArticleService.insertBatch(fieldList);
		}
		return RestResponse.success();
	}
	
	@PostMapping("delete")
	@ResponseBody
	public RestResponse delete(@RequestParam("ids[]")List<Long> ids){
		if(ids == null || ids.size() == 0){
			return RestResponse.failure("删除ID不能为空");
		}
		List<Article>  list = articleService.selectBatchIds(ids);
		for (Article article : list) {
			article.preUpdate();
			article.setIsDel(true);
		}
		articleService.insertOrUpdateBatch(list);
		return RestResponse.success();
	}
}
